﻿/*----------------------------------------------------------*/
/*--- Standard javascript code of Roanoke's SDI Web Site ---*/
/*----------------------------------------------------------*/

/*------------------------*/
/*
    Global object:
        Each of its property can be setted before or after the Standard.js is loaded. But Some
    properties has its right place and moment to be setted.
*/
/*-----------------------*/

//#region Global object

if(!window.Global)
    window.Global = {};
/* AfterDomReady: a list of handlers to be exectuded after the real DOM Ready event is fired. */
if(!Global.AfterDomReady)
    Global.AfterDomReady = [];
/* CheckIfUserIsLoggedInterval: the interval to wait after the system check if the current user keep logged. */
if (!Global.CheckIfUserIsLoggedInterval)
    Global.CheckIfUserIsLoggedInterval = 30 * 1000;
/* ConnectionStringNames: a collection of the connection string names used in the system. */
if(!Global.ConnectionStringNames)
    Global.ConnectionStringNames = {};
/* SDIMes connection string name. */
if(!Global.ConnectionStringNames.SDIMes)
    Global.ConnectionStringNames.SDIMes = "SDIMes";
/* IHServer connection string name. */
if(!Global.ConnectionStringNames.IHServer)
    Global.ConnectionStringNames.IHServer = "IHServer";
if(!Global.ConnectionStringNames.IHServerPLT)
    Global.ConnectionStringNames.IHServerPLT = "IHServerPLT";
/* PLT connection string name. */
if(!Global.ConnectionStringNames.PLT)
    Global.ConnectionStringNames.PLT = "PLT";
/* DefaultURL: the default url to be loaded at the start. */
if(!Global.DefaultURL)
    Global.DefaultURL = "Reports/MeltshopProduction.html";
/* DalService URL. */
if(!Global.DALServiceURL)
    Global.DALServiceURL = "/IndustrialDashboard/DALService.svc/";
/* GlobalScreenRef: A reference to the attributes of the Global window object. */
if(!Global.GlobalScreenRef)
    Global.GlobalScreenRef = null;
/* Includer instance. */
if(!Global.Includer)
    Global.Includer = {};
/* IframeUN: an instance of the class URLNavigator with the history of the iframe. */
if(!Global.IframeUN)
    Global.IframeUN = null;
/* IsGlobalWindow: indicates if this window is the Global window. */
if(!Global.IsGlobalWindow)
    Global.IsGlobalWindow = undefined;
/* IsTesting: indicates if the system is running in TESTING mode. */
if((Global.IsTesting == undefined) || (Global.IsTesting == null))
    Global.IsTesting = false;
/* MESService URL. */
if(!Global.MESServiceURL)
    Global.MESServiceURL = "/MESService/MES.svc/json/";
/* Security: an instance of the class SecurityLogin. */
if(!Global.Security)
    Global.Security = {};
/* Roles: a collection of all the security roles of the system. */
if(!Global.Roles)
    Global.Roles = { MESAdminRole: "MESAdminRole", MESEAFOperatorRole: "MESEAFOperatorRole", MESLFOperatorRole: "MESLFOperatorRole", MESCasterOperatorRole: "MESCasterOperatorRole", MESOperatorRole: "MESOperatorRole", MESRefractoryRole: "MESRefractoryRole" };
/* Screen: an object related to the screen. */
if(!Global.Screen)
    Global.Screen = {};
/* Screen.ScreenToolbar: an object related to the global toolbar. */
if(!Global.Screen.ScreenToolbar)
    Global.Screen.ScreenToolbar = {};
/* Screen.ScreenToolbar.Enable: enable or not the global toolbar. */
if((Global.Screen.ScreenToolbar.Enable == undefined) || (Global.Screen.ScreenToolbar.Enable == null))
    Global.Screen.ScreenToolbar.Enable = true;
/* Screen.ScreenToolbar.ExporterBar: an object related to the exporter bar of the global toolbar. */
if(!Global.Screen.ScreenToolbar.ExporterBar)
    Global.Screen.ScreenToolbar.ExporterBar = {};
/* Screen.ScreenToolbar.ExporterBar.IconBarInstance: an instance of the class IconBar wich contains the icons of export to excel and pdf. */
if(!Global.Screen.ScreenToolbar.ExporterBar.IconBarInstance)
    Global.Screen.ScreenToolbar.ExporterBar.IconBarInstance = null;
/* Screen.ScreenToolbar.ExporterBar.Enable: enable or not the ExporterBar. */
if((Global.Screen.ScreenToolbar.ExporterBar.Enable == undefined) || (Global.Screen.ScreenToolbar.ExporterBar.Enable == null))
    Global.Screen.ScreenToolbar.ExporterBar.Enable = true;
/* Screen.ScreenToolbar.ExporterBar.ExcelHandler: the excel exportation method to be used. */
if(!Global.Screen.ScreenToolbar.ExporterBar.ExcelHandler)
    Global.Screen.ScreenToolbar.ExporterBar.ExcelHandler = function(){};
/* Screen.ScreenToolbar.ExporterBar.PDFHandler: the pdf exportation method to be used. */
if(!Global.Screen.ScreenToolbar.ExporterBar.PDFHandler)
    Global.Screen.ScreenToolbar.ExporterBar.PDFHandler = function(){};
/* Screen.ScreenToolbar.NavigationBar: an object related to the global navigation bar of the global toolbar. */
if(!Global.Screen.ScreenToolbar.NavigationBar)
    Global.Screen.ScreenToolbar.NavigationBar = {};
/* Screen.ScreenToolbar.NavigationBar.Enable: enable or not the NavigationBar. */
if((Global.Screen.ScreenToolbar.NavigationBar.Enable == undefined) || (Global.Screen.ScreenToolbar.NavigationBar.Enable == null))
    Global.Screen.ScreenToolbar.NavigationBar.Enable = true;
/* Screen.ScreenToolbar.SectionsCount: Screen.ScreenToolbar's sections count. */
if(!Global.Screen.ScreenToolbar.SectionsCount)
    Global.Screen.ScreenToolbar.SectionsCount = 2;
/* Screen.ScreenToolbar.SectionsList: a list with the reference to the DOM object of the refScreenToolbar's sections. */
if(!Global.Screen.ScreenToolbar.SectionsList)
    Global.Screen.ScreenToolbar.SectionsList = [];
/* Screen.TitleContainer: a reference to the DOM object of the title of the screen. */
if(!Global.Screen.TitleContainer)
    Global.Screen.TitleContainer = null;

/* Set all Global dom objects. */
attachDomReadyEventHandler(function () {
    try {
        /* Clear windows status. */
        ShowStatus("");

        if ((window.parent.Global == undefined) || (window.parent.Global.IsGlobalWindow == undefined)) {
            Global.IsGlobalWindow = true;

            Global.Security = SecurityLogin;

            Global.Screen.TitleContainer =
            Global.Screen.TitleContainer = document.getElementById("screensTitle");

            var screenIframe = document.getElementById("screenIframe");
            Global.IframeUN = new URLNavigator(screenIframe, null);
        }
        else {
            Global.IsGlobalWindow = false;

            Global.GlobalScreenRef = window.parent.Global.GlobalScreenRef;

            Global.Security = window.parent.Global.Security;

            Global.Screen.TitleContainer = window.parent.Global.Screen.TitleContainer;

            if(Global.Screen.TitleContainer)
                Global.Screen.TitleContainer.innerHTML = window.document.title;

            Global.IframeUN = window.parent.Global.IframeUN;

            //#region Draw ScreenToolbar's sections.

            if (Global.Screen.ScreenToolbar.Enable == true) {
                var Toolbar = document.getElementById("ScreenToolbar");

                var sectionsCount = ((Toolbar.attributes.getNamedItem("SectionsCount")) && (parseInt(Toolbar.attributes.getNamedItem("SectionsCount").value)))
                                        ? parseInt(Toolbar.attributes.getNamedItem("SectionsCount").value)
                                        : Global.Screen.ScreenToolbar.SectionsCount;

                var tsWidthPercentage = parseInt(100 / sectionsCount).toString() + "%";

                for (var sectionIndex = 1; sectionIndex <= sectionsCount; sectionIndex++) {
                    var toolbarSection = document.createElement("div");
                    toolbarSection.className = "ToolbarSection";
                    /* The unique style's property setted in javascript will be the "width" property depending the ScreenToolbar's sections count. */
                    toolbarSection.style.width = tsWidthPercentage;
                    Toolbar.appendChild(toolbarSection);

                    Global.Screen.ScreenToolbar.SectionsList.push(toolbarSection);
                }

                /* Decrement in one unit the percentage of the last section width. */
                Global.Screen.ScreenToolbar.SectionsList[Global.Screen.ScreenToolbar.SectionsList.length - 1].style.width =
                    (parseInt(Global.Screen.ScreenToolbar.SectionsList[Global.Screen.ScreenToolbar.SectionsList.length - 1].style.width) - 1).toString() + "%";

                /* The first ScreenToolbar' sections is always for NavigationBar if it is enable. */
                if (Global.Screen.ScreenToolbar.NavigationBar.Enable == true) {
                    var navigationIBContainer = document.createElement("div");
                    navigationIBContainer.id = "navigationBar";

                    /* Create an Instance of Icons Bar. */
                    Global.Screen.ScreenToolbar.NavigationBar.IconBarInstance = new IconsBar(navigationIBContainer);
                    Global.Screen.ScreenToolbar.NavigationBar.IconBarInstance.AddIcon(
                        { IconName: "Left", Title: "Go backward", Action: function () { Global.IframeUN.Back(); } });
                    Global.Screen.ScreenToolbar.NavigationBar.IconBarInstance.AddIcon(
                        { IconName: "Right", Title: "Go forward", Action: function () { Global.IframeUN.Forward(); } });

                    if (Global.IsTesting == true) {
                        Global.Screen.ScreenToolbar.NavigationBar.IconBarInstance.AddIcon(
                            { IconName: "Refresh1", Title: "Refresh screen", Action: function () { window.location.reload() } });
                    }

                    Global.Screen.ScreenToolbar.SectionsList[0].appendChild(navigationIBContainer);
                }

                /* The first ScreenToolbar' sections is always for ExporterBar if it is enable. */
                if (Global.Screen.ScreenToolbar.ExporterBar.Enable == true) {
                    var exporterIBContainer = document.createElement("div");
                    exporterIBContainer.id = "exporterBar";

                    /* Create an Instance of Icons Bar. */
                    Global.Screen.ScreenToolbar.ExporterBar.IconBarInstance = new IconsBar(exporterIBContainer);
                    //                    Global.Screen.ScreenToolbar.ExporterBar.IconBarInstance.AddIcon(
                    //                        { IconName: "PDF", Title: "Export to PDF", Action: Global.Screen.ScreenToolbar.ExporterBar.PDFHandler });
                    Global.Screen.ScreenToolbar.ExporterBar.IconBarInstance.AddIcon(
                        { IconName: "Excel", Title: "Export to Excel", Action: Global.Screen.ScreenToolbar.ExporterBar.ExcelHandler });
                    /* Block ExporterBar until the widgets be initialized. */
                    Global.Screen.ScreenToolbar.ExporterBar.IconBarInstance.BlockIcons();

                    Global.Screen.ScreenToolbar.SectionsList[Global.Screen.ScreenToolbar.SectionsList.length - 1].appendChild(exporterIBContainer);
                }
            }

            //#endregion
        }

        for (var handlerIndex = 0; handlerIndex < Global.AfterDomReady.length; handlerIndex++) {
            /* 
                Use a own try/catch block to not depends from the handler scripting.
                Also to prevent not fire the rest of handlers.
            */
            try {
                Global.AfterDomReady[handlerIndex]();
            }
            catch (Error) { ShowError(Error); }
        }
    }
    catch (Error) { ShowError(Error); }
}, Global.Includer);

//#region Methods

function ExecuteProcedure(privateParameters, parameters, onSuccessHandler, onFailureHandler) {
    var options = { data: {} };
    options.data.DatabaseParameters = privateParameters.DatabaseParameters;
    options.data.JSONFile = privateParameters.JSONFile;
    for (var conParam in privateParameters.ConnectionParameters)
        options[conParam] = privateParameters.ConnectionParameters[conParam];
    if ((parameters) && (parameters.Version))
        options.data.DatabaseParameters.QueryParameters = parameters.GetQueryParameters();
    else options = (parameters) ? parameters : options;

    options.data.Namespace = privateParameters.Version.Namespace;
    options.data.Class = privateParameters.Version.Class;

    options.onSuccess = function (requestData) {
        if ((requestData) && (!requestData.message)) {
            if (onSuccessHandler)
                onSuccessHandler(requestData);
        }
        else if ((requestData) && (requestData.message)) {
            requestData.text = requestData.message;

            if (onFailureHandler)
                onFailureHandler(requestData);
            else
                ShowError(requestData.text);
        }
        else {
            requestData.text = "Fail to execute " + privateParameters.DatabaseParameters.Procedure;

            if (onFailureHandler)
                onFailureHandler(requestData);
            else
                ShowError(requestData.text);
        }
    };
    options.onFailure = function (requestData) {
        if(onFailureHandler)
            onFailureHandler(requestData);
        else
            ShowError(requestData.text);
    };

    RequestJSON(privateParameters.URL + privateParameters.Method, options);
}
function GetLastBaseProperty(obj) {
    try {
        if(!obj.Base)
        {
            obj.Base = {};
            return obj.Base;
        }
        else
        {
            return arguments.callee(obj.Base);
        }
    }
    catch(Error) { ShowError(Error); }
};
Global.FormatNullDDPValue = function (value) {
    try {
        if(value == "")
            return "0";
    }
    catch(Error) { ShowError(Error); }
    return value;
}
function GetDOMObjectRealHeight(domObject) {
    try
    {        
		return ("scrollTo" in domObject && domObject.document) 
            ? // does it walk and quack like a window?
			    // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			    domObject.document.compatMode === "CSS1Compat" && domObject.document.documentElement.clientHeight || domObject.document.body.clientHeight 
            :
			// Get document Height or height
			(domObject.nodeType === 9) ? // is it a document
				// Either scrollHeight or offsetHeight, whichever is greater
				Math.max(
					domObject.documentElement.clientHeight,
					domObject.body.scrollHeight, domObject.documentElement.scrollHeight,
					domObject.body.offsetHeight, domObject.documentElement.offsetHeight
				) : parseInt(domObject.style.height);
    }
    catch (Error) { ShowError(Error) }
}
function GetDOMObjectRealWidth(domObject) {
    try
    {        
		return ("scrollTo" in domObject && domObject.document) 
            ? // does it walk and quack like a window?
			    // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			    domObject.document.compatMode === "CSS1Compat" && domObject.document.documentElement.clientWidth || domObject.document.body.clientWidth 
            :
			// Get document width or height
			(domObject.nodeType === 9) ? // is it a document
				// Either scrollWidth or offsetWidth, whichever is greater
				Math.max(
					domObject.documentElement.clientWidth,
					domObject.body.scrollWidth, domObject.documentElement.scrollWidth,
					domObject.body.offsetWidth, domObject.documentElement.offsetWidth
				) : parseInt(domObject.style.width);
    }
    catch (Error) { ShowError(Error) }
}
Global.FillFWContainersList = function(fwContainersList, domObjectParent) {
    try {
        for (var childIndex = 0; childIndex < domObjectParent.childNodes.length; childIndex++) {
            var domObjectChild = domObjectParent.childNodes[childIndex];

            if ((domObjectChild.attributes) && (domObjectChild.attributes.getNamedItem("IsFormWidget"))
                && (Trim(domObjectChild.attributes.getNamedItem("IsFormWidget").value).toUpperCase() == "TRUE")) {
                fwContainersList.push(domObjectChild);
            }

            Global.FillFWContainersList(fwContainersList, domObjectChild);
        }
    }
    catch(Error) { ShowError(Error) ; }
}
function GetHeatAttributes(heatNumber, onSuccess, async, onFailure) {
    try {
        var errorMSG = "Could not get heat attributes";
        var privateParameters = new PrivateParameters(
        {
            URL: Global.DALServiceURL
//            , ConnectionParameters: { Async: ((async != undefined) && (async != null))
//                                                    ? async
//                                                    : true }
            , ConnectionParameters: { Async: async || true  }
            , DatabaseParameters: { ConnectionStringName: Global.ConnectionStringNames.SDIMes, Procedure: "dbo.GetHeatAttributes" }
        });
        privateParameters.Version.Class = null;

        var qp = new QueryParameters();
        qp.Add("HeatNumber", "VARCHAR", heatNumber);

        ExecuteProcedure(
            privateParameters
            , qp
            , function(requestData) {
                ValidateServiceData({
                    ErrorMSG: errorMSG
                    , RequestData: requestData
                    , Validated: onSuccess
                    , Invalidated: onFailure
                });
            }
            , onFailure
        );
    }
    catch(Error)
    { 
//        if((onFailure != undefined) && (onFailure != null))
//            onFailure(errorMSG + ": " + Error.Message);
//        else
//            ShowError(errorMSG + ": " + Error.Message);
        (onFailure || ShowError)(errorMSG + ": " + Error.Message);
    }
}
Global.IsChildNodeOf = function IsChildNodeOf(parent, childToFind) {
    try {
        if (parent.children.length > 0) {
            for (var iChild = 0; iChild < parent.children.length; iChild++) {
                if (parent.children[iChild] == childToFind)
                    return true;
                else
                    if (arguments.callee(parent.children[iChild], childToFind) == true)
                        return true;
            }
        }
    }
    catch (Error) { ShowError(Error); }
    return false;
};
function GetLineName() {
    var lineName = "";
    try
    {
        var lineNumber = parseInt(PageQuery.GetItem("LineID"));

        switch(lineNumber)
        {
            case 1:
                lineName = "EAF";
                break;
            case 2:
                lineName = "LF";
                break;
            case 3:
                lineName = "Caster";
                break;
            default:
                break;
        }
    }
    catch (Error) { ShowError(Error) }
    return lineName;
}
function ParseTreatmentNumber(treatmentNumber) {
    var result = { HeatNumber: null, Treatment: null };
    try {
        if (treatmentNumber) {
            var splitList = treatmentNumber.split(".");

            if (splitList.length == 2) {
                result.HeatNumber = splitList[0];
                result.Treatment = splitList[1];
            }
        }
    }
    catch (Error) { ShowError(Error); }
    return result;
}
Global.GetLadleByArea = function (areaName) {
    var ladleID = null;
    try {
        var errorMSG = "Could not get ladle";

        var privateParameters = new PrivateParameters(
        {
            URL: Global.DALServiceURL
            , ConnectionParameters: { Async: false }
            , DatabaseParameters: { ConnectionStringName: Global.ConnectionStringNames.PLT, Procedure: "dbo.GetLadlesByArea" }
        });

        privateParameters.Version.Class = null;

        var qp = new QueryParameters();
        qp.Add("@Area", "VARCHAR", Trim(areaName));

        ExecuteProcedure(
            privateParameters
            , qp
            , function (requestData) {
                try {
                    if((requestData.Table) && (requestData.Table.length > 0))
                        ladleID = parseInt(requestData.Table[0].Ladle);
                }
                catch(Error) { ShowError(Error); }
            }
            , function (requestData) {
                try {
                    ShowError(errorMSG + ": " + requestData.text);
                }
                catch(Error) { ShowError(Error); }
            }
        );
    }
    catch(Error) { ShowError(Error); }
    return ladleID;
}
function ShowError(error) {
    try {
        var errorMSG = ((error.message != undefined) && (error.message != null))
                            ? error.message
                            : error;

        if(Global.IsTesting)
            alert(errorMSG);
        else
            window.status = errorMSG;
    }
    catch (Error) { window.status = Error.Message; }
}
function ShowStatus(message, delay) {
    try 
    {
        if(!delay)
            delay = 5000;

        window.status = message;
        setTimeout(function () 
        { 
            try
            {
                window.status = ""; 
            }
            catch (Error) { ShowError(Error) }

        }, delay);
    }
    catch (Error) { ShowError(Error) }
};
function ValidateDALServiceResponse(options) {
    try 
    {
        if(!options.ErrorMSG)
            options.ErrorMSG = "Service error"

        if(!options.RequestData)
        {
            ShowError(options.ErrorMSG);
            return;
        }
        else
        {
            if(!options.RequestData)
            {
                ShowStatus(options.ErrorMSG);
                return;
            }
            else {
                if ((options.RequestData.ResponseID == undefined) || (options.RequestData.ResponseID == null) || (options.RequestData.ResponseID != 0))
                {
                    ShowError(options.ErrorMSG
                                    + ((options.RequestData.Message)
                                        ? ": " + options.RequestData.Message
                                        : "."));
                    
                    if(options.Invalidated)
                        options.Invalidated(options.RequestData);

                    return;
                }
                else
                {
                    if(options.Validated)
                        options.Validated(options.RequestData);
                    return;
                }
            }
        } 
    }
    catch (Error) { ShowError(options.ErrorMSG + ". Error" + Error.message) }
}
function ValidateServiceData(options) {
    try 
    {
        if(!options.ErrorMSG)
            options.ErrorMSG = "Service error"

        if(!options.RequestData)
        {
            ShowStatus(options.ErrorMSG);
            return;
        }
        else
        {
            var data = null;
            for (var prop in options.RequestData)
                data = options.RequestData[prop];

            if(data == null)
            {
                ShowError(new Error(options.ErrorMSG));

                if(options.Invalidated)
                    options.Invalidated(data);
                return;
            }
            else
            {
                if(options.Validated)
                    options.Validated(data);
                return;
            }
        } 
    }
    catch (Error) { ShowError(Error) }
};
function ValidateServiceResponse(options) {
    try 
    {
        if(!options.ErrorMSG)
            options.ErrorMSG = "Service error"

        if(!options.RequestData)
        {
            ShowError(options.ErrorMSG);
            return;
        }
        else
        {
            var response = null;
            for (var prop in options.RequestData)
                response = options.RequestData[prop];

            if(response == null)
            {
                ShowStatus(options.ErrorMSG);
                return;
            }
            else {
                if ((response.ID == undefined) || (response.ID == null) || (response.ID != 0))
                {
                    ShowError(options.ErrorMSG
                                    + ((response.Message)
                                        ? ": " + response.Message
                                        : "."));

                    if(options.Invalidated)
                        options.Invalidated(response);

                    return;
                }
                else
                {
                    if(options.Validated)
                        options.Validated(response);
                    return;
                }
            }
        } 
    }
    catch (Error) { ShowError(options.ErrorMSG + ". Error" + Error.message) }
};

Array.prototype.indexOf = function (s) {
    for (var x = 0; x < this.length; x++) 
        if (this[x] == s) 
            return x;
    return -1;
}

//#endregion

//#region Grids

Global.Grids = (function(){
    function _Grid() {
        try {
            //#region Private stuff

            var MYREFERENCE = {};

            //#region Methods



            //#endregion

            //#endregion

            //#region Public Stuff

            this.GetTorchBilletIG = function(gridContainer, newOptions) {
                try {
                    var defaultOptions = {
                        ExtAttributes:{
                            GridOptions: {
                                DatabaseParameters: { Procedure: "dbo.CasterGetTorchBillet" }
                                , Export: { OutputFileName: "Torch System Billets" }
                                , View: { Title: "Torch System Billets" }
                            }
                        }
                    }

                    newOptions = _Grid.ExtendOptions(newOptions, defaultOptions);

                    var PRIVATEPARAMETERS = new _Grid.GridIGBase(newOptions);

                    PRIVATEPARAMETERS.Initialize(gridContainer);

                    return PRIVATEPARAMETERS.Grid;
                }
                catch(Error) { ShowError(Error); }
                return null;
            };
            this.GetBilletsSG = function(gridContainer, newOptions) {
                try {
                    var defaultOptions = {
                        ExtAttributes:{
                            GridOptions: {
                                URL:Global.DALServiceURL + "CallProcedure"
                                , Attributes:{ autoHeight:true }
                                , DatabaseParameters:{ Procedure: "dbo.CasterTorchBilletsSG" }
                                , Title:"Billets"
                            }
                        }
                    };

                    newOptions = _Grid.ExtendOptions(newOptions, defaultOptions);

                    var PRIVATEPARAMETERS = new _Grid.GridISGBase(newOptions);

                    PRIVATEPARAMETERS.Initialize(gridContainer);

                    return PRIVATEPARAMETERS.Grid;
                }
                catch(Error) { ShowError(Error); }
                return null;
            };
            this.GetChemistrySamplesSG = function(gridContainer, newOptions) {
                try {
                    var defaultOptions = {
                        ExtAttributes:{
                            Editable:false
                            , GetGradesSpecification:function(heatNumber) {
                                try {
                                    var errorMSG = "Could not get grades specification.";

                                    var privateParameters = new PrivateParameters(
                                    {
                                        URL: Global.DALServiceURL
                                        , ConnectionParameters: { Async: false }
                                        , DatabaseParameters: { ConnectionStringName: Global.ConnectionStringNames.SDIMes, Procedure: "dbo.LabGetGradeSpecs" }
                                    });
                                    privateParameters.Version.Class = null;

                                    var qp = new QueryParameters();
                                    qp.Add("HeatNumber", "VARCHAR", heatNumber);
                                    qp.Add("GetAllVersions", "BIT", true);

                                    ExecuteProcedure(
                                        privateParameters
                                        , qp
                                        , function (requestData) {
                                            ValidateServiceData({
                                                ErrorMSG: errorMSG
                                                , RequestData: requestData
                                                , Validated: function (data) {
                                                    PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification = {};

                                                    for(var iGradeSpec = 0; iGradeSpec < data.length; iGradeSpec++)
                                                    {
                                                        try {
                                                            var gradeSpec = data[iGradeSpec];

                                                            var gradeID = gradeSpec.GradeID.toString();
                                                            var specVersion = gradeSpec.SpecVersion.toString();
                                                            var specTypeCode = Trim(gradeSpec.SpecTypeCode).toUpperCase();
                                                            var ecsi = gradeSpec.ECSI; /* Element Columns Start Index. */

                                                            if(!PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[gradeID])
                                                                PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[gradeID] = {};
                                                            if(!PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[gradeID][specVersion])
                                                                PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[gradeID][specVersion] = {};

                                                            var iColumn = 0
                                                            for(var element in gradeSpec)
                                                            {
                                                                try {
                                                                    if(iColumn != ecsi)
                                                                    {
                                                                        iColumn++;
                                                                        continue;
                                                                    }
                                                                    else
                                                                    {
                                                                        if(!PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[gradeID][specVersion][element])
                                                                            PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[gradeID][specVersion][element] = { L:null, A:null, U:null };

                                                                        PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[gradeID][specVersion][element][specTypeCode] = gradeSpec[element];
                                                                    }
                                                                }
                                                                catch (Error) { ShowError(Error); }
                                                            }
                                                        }
                                                        catch (Error) { ShowError(Error); }
                                                    }
                                                }
                                                , Invalidated: function (requestData) {
                                                    ShowError(errorMSG + ": " + requestData.text);
                                                }
                                            });
                                        }
                                        , function (requestData) {
                                            ShowError(errorMSG + ": " + requestData.text);
                                        }
                                    );
                                }
                                    catch (Error) { ShowError(Error); }
                                }
                            , GradesSpecification:{}
                            , GridOptions:{
                                URL:Global.DALServiceURL + "CallProcedure"
                                , Attributes:{ autoHeight:true, editable:false, enableCellNavigation:false }
                                , DatabaseParameters:{ Procedure:"dbo.LabSamplesSG" }
                                , Title:"Samples"
                            }
                            , RowSelected:null
                            , SampleFormatter:function(row, cell, value, columnDef, dataContext) {
                                try {
                                    var element = null;
                                    var columnIndex = 0; /* Start form -1 because the id column does not count. */

                                    for(var columnName in dataContext)
                                    {
                                        if(columnIndex != cell)
                                        {
                                            columnIndex++;
                                        }
                                        else
                                        {
                                            element = columnName;
                                            break;
                                        }
                                    }

                                    var gradeSpec = ((PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[dataContext.GradeID.toString()]) && (PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[dataContext.GradeID.toString()][dataContext.SpecVersion.toString()]) && (PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[dataContext.GradeID.toString()][dataContext.SpecVersion.toString()][element]))
                                                        ? PRIVATEPARAMETERS.Grid.ExtAttributes.GradesSpecification[dataContext.GradeID.toString()][dataContext.SpecVersion.toString()][element]
                                                        : { L:null, A:null, U:null };
        //                            var isAim = true;

                                    var spanHTMLString = "<span style=\"";
                                    var valueFloat = parseFloat(value);

                                    /* Do not use CSS Classes because it does not work. Only style span's tag. */
                                    var styleSampleValueAim =       "background-color:transparent;color:#000000;display:inline-block;";
                                    var styleSampleValueBelowAim =  "background-color:transparent;color:#000000;display:inline-block;";//"background-color:transparent;color:#FF7F50;display:inline-block;font-weight:bold;";
                                    var styleSampleValueBelowMin =  "height:100%;width:100%;background-color:#BDB76B;color:#FFFFFF;display:inline-block;font-weight:bold;";
                                    var styleSampleValueOverMax =   "height:100%;width:100%;background-color:#FF4500;color:#FFFFFF;display:inline-block;font-weight:bold;";

                                    var lower = ((gradeSpec) && (gradeSpec.L != null) && (gradeSpec.L != undefined))
                                                            ? parseFloat(gradeSpec.L)
                                                            : -Infinity;
                                    var aim = ((gradeSpec) && (gradeSpec.A != null) && (gradeSpec.A != undefined))
                                                            ? parseFloat(gradeSpec.A)
                                                            : -Infinity;
                                    var upper = ((gradeSpec) && (gradeSpec.U != null) && (gradeSpec.U != undefined))
                                                            ? parseFloat(gradeSpec.U)
                                                            : Infinity;

                                    if(valueFloat < lower)
                                    {
                                        spanHTMLString += styleSampleValueBelowMin;
        //                                isAim = false;
                                    }
                                    else if(valueFloat < aim)
                                    {
                                        spanHTMLString += styleSampleValueBelowAim;
                                    }
                                    else if(valueFloat > upper)
                                    {
                                        spanHTMLString += styleSampleValueOverMax;
        //                                isAim = false;
                                    }
                                    else
                                    {
                                        spanHTMLString += styleSampleValueAim;
                                    }

                                    if(((columnDef.SpecialData) && (columnDef.SpecialData.ML) && (columnDef.SpecialData.ML.toString().match(dataContext.SampleID.toString()))))
                                    {
        //                                spanHTMLString = spanHTMLString.replace(
        //                                                    /;color:.{7}/
        //                                                    , (isAim)
        //                                                        ? ";color:#2E8B57"
        //                                                        : ";color:#90EE90");

                                        if(!columnDef.SpecialData.ML)
                                            columnDef.SpecialData.ML = dataContext.SampleID.toString();
                                        else if(!columnDef.SpecialData.ML.toString().match(dataContext.SampleID.toString()))
                                            columnDef.SpecialData.ML = columnDef.SpecialData.ML.toString() + ", " + dataContext.SampleID.toString();
                                    }

                                    spanHTMLString += "\">" 
                                                    + ((isNaN(valueFloat))
                                                            ? ""
                                                            : parseFloat(value).toFixed(4))
                                                        + "</span>";

                                    return spanHTMLString;
                                }
                            catch (Error) { ShowError(Error); }
                            return value;
                        }
                        }
                    };

                    newOptions = _Grid.ExtendOptions(newOptions, defaultOptions);

                    var PRIVATEPARAMETERS = new _Grid.GridISGBase(newOptions);

                    PRIVATEPARAMETERS.Initialize(gridContainer);

                    return PRIVATEPARAMETERS.Grid;
                }
                catch(Error) { ShowError(Error); }
                return null;
            };
            this.GetEAFSamplesSlagSG = function(gridContainer, newOptions) {
                try {
                    var defaultOptions = {
                        ExtAttributes:{
                            Editable:false
                            , GridOptions:{
                                URL:Global.DALServiceURL + "CallProcedure"
                                , Attributes:{ autoHeight:true, editable:false, enableCellNavigation:false }
                                , DatabaseParameters:{ Procedure:"dbo.LabEAFSamplesSlagSG" }
                                , Title:"EAF Slag Samples"
                            }
                        }
                    };

                    newOptions = _Grid.ExtendOptions(newOptions, defaultOptions);

                    var PRIVATEPARAMETERS = new _Grid.GridISGBase(newOptions);

                    PRIVATEPARAMETERS.Initialize(gridContainer);

                    return PRIVATEPARAMETERS.Grid;
                }
                catch(Error) { ShowError(Error); }
                return null;
            };

            //#endregion
        }
        catch(Error) { ShowError(Error); }
    }

    //#region  Public Static stuff
    
    //#region  Methods

    _Grid.ExtendOptions = function(defaultOptions, newOptions) {
        try {
            if (!newOptions)
                newOptions = {};

            if (defaultOptions)
                ObjectExtend(defaultOptions, newOptions);

            return newOptions;
        }
        catch(Error) { ShowError(Error); }
        return null;
    };

    //#endregion

    //#region Structs

    _Grid.GridBase = function(options, object) {
        try {
            object = _Grid.ExtendOptions(options, object);

            if (!options)
                options = {};

            if(!object.ExtAttributes)
                object.ExtAttributes = {};
            if(!object.ExtAttributes.GridOptions)
                object.ExtAttributes.GridOptions = {};
            if(!object.ExtAttributes.GridOptions.URL)
                object.ExtAttributes.GridOptions.URL = Global.DALServiceURL;
            else
                object.ExtAttributes.GridOptions.URL = Trim(object.ExtAttributes.GridOptions.URL);
            if(!object.ExtAttributes.GridOptions.DatabaseParameters)
                object.ExtAttributes.GridOptions.DatabaseParameters = {};
            if(!object.ExtAttributes.GridOptions.DatabaseParameters.ConnectionStringName)
                object.ExtAttributes.GridOptions.DatabaseParameters.ConnectionStringName = Global.ConnectionStringNames.SDIMes;
            else
                object.ExtAttributes.GridOptions.DatabaseParameters.ConnectionStringName = Trim(object.ExtAttributes.GridOptions.DatabaseParameters.ConnectionStringName);
            if(!object.ExtAttributes.GridOptions.DatabaseParameters.Procedure)
                object.ExtAttributes.GridOptions.DatabaseParameters.Procedure = "";
            else
                object.ExtAttributes.GridOptions.DatabaseParameters.Procedure = Trim(object.ExtAttributes.GridOptions.DatabaseParameters.Procedure);
            if(!object.ExtAttributes.GridOptions.Events)
                object.ExtAttributes.GridOptions.Events = {};
            if(!object.ExtAttributes.GridOptions.Events.onError)
                object.ExtAttributes.GridOptions.Events.onError = ShowError;

            object.Grid = null;

            return object;
        }
        catch(Error) { ShowError(Error); }
        return null;
    }
    _Grid.GridIGBase = function(options, object) {
        try {
            object = _Grid.GridBase(options, object);

            if (!options)
                options = {};

            object.Initialize = function (container) {
                try {
                    object.Grid = new IndustrialGrid(container, object.ExtAttributes.GridOptions);

                    object.Grid.ExtAttributes = object.ExtAttributes;
                }
                catch(Error){ ShowError(Error); }
            }

            if(!object.ExtAttributes.GridOptions.Export)
                object.ExtAttributes.GridOptions.Export = {};
            if(!object.ExtAttributes.GridOptions.Export.OutputFileName)
                object.ExtAttributes.GridOptions.Export.OutputFileName = "";
            else
                object.ExtAttributes.GridOptions.Export.OutputFileName = Trim(object.ExtAttributes.GridOptions.Export.OutputFileName);
            if(!object.ExtAttributes.GridOptions.Export.Source)
                object.ExtAttributes.GridOptions.Export.Source = "SERVERCURRENTVIEW";
            else
                object.ExtAttributes.GridOptions.Export.Source = Trim(object.ExtAttributes.GridOptions.Export.Source);
            if(!object.ExtAttributes.GridOptions.View)
                object.ExtAttributes.GridOptions.View = {};
            if((object.ExtAttributes.GridOptions.View.Legend == undefined) || (object.ExtAttributes.GridOptions.View.Legend == null))
                object.ExtAttributes.GridOptions.View.Legend = false;
            if(!object.ExtAttributes.GridOptions.View.Title)
                object.ExtAttributes.GridOptions.View.Title = "";
            else
                object.ExtAttributes.GridOptions.View.Title = Trim(object.ExtAttributes.GridOptions.View.Title);

            return object;
        }
        catch(Error) { ShowError(Error); }
        return null;
    }
    _Grid.GridISGBase = function(options, object) {
        try {
            object = _Grid.GridBase(options, object);

            if (!options)
                options = {};

            object.Initialize = function (gridContainer) {
                try {
                    object.Grid = new IndustrialSlickGrid(gridContainer, object.ExtAttributes.GridOptions);

                    object.Grid.ExtAttributes = object.ExtAttributes;

                    addEventHandler(gridContainer, "onclick", object.ISGContainers_Click);
                }
                catch(Error){ ShowError(Error); }
            }
            object.ISGContainers_Click = function (e) { 
                try
                {
                    if (document.all)
                        window.event.cancelBubble = true;
                    // e.stopPropagation works in standar browsers. //
                    else if (e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                    }
                }
                catch(Error) { ShowError(Error); }
            };
            object.ISGMode_CellBlur = function () {
                try {
                    object.ExtAttributes.Focused = false;
                }
                catch(Error){ ShowError(Error); }
            };
            object.ISGMode_Complete = function () {
                try {
                    object.Grid.SetEditable(object.ExtAttributes.Editable);
                }
                catch (Error) { ShowError(Error); }
            };

            if(!object.ExtAttributes.GridOptions.Attributes)
                object.ExtAttributes.GridOptions.Attributes = {};
            if((object.ExtAttributes.GridOptions.Attributes.AllowDelete == undefined) || (object.ExtAttributes.GridOptions.Attributes.AllowDelete == null))
                object.ExtAttributes.GridOptions.Attributes.AllowDelete = true;
            if(!object.ExtAttributes.GridOptions.Attributes.defaultColumnWidth)
                object.ExtAttributes.GridOptions.Attributes.defaultColumnWidth = 90;
            if((object.ExtAttributes.GridOptions.Attributes.editable == undefined) || (object.ExtAttributes.GridOptions.Attributes.editable == null))
                object.ExtAttributes.GridOptions.Attributes.editable = true;
            if((object.ExtAttributes.GridOptions.Attributes.enableAddRow == undefined) || (object.ExtAttributes.GridOptions.Attributes.enableAddRow == null))
                object.ExtAttributes.GridOptions.Attributes.enableAddRow = true;
            if((object.ExtAttributes.GridOptions.Attributes.enableCellNavigation == undefined) || (object.ExtAttributes.GridOptions.Attributes.enableCellNavigation == null))
                object.ExtAttributes.GridOptions.Attributes.enableCellNavigation = true;
            if((object.ExtAttributes.GridOptions.Attributes.enableColumnReorder == undefined) || (object.ExtAttributes.GridOptions.Attributes.enableColumnReorder == null))
                object.ExtAttributes.GridOptions.Attributes.enableColumnReorder = true;
            if((object.ExtAttributes.GridOptions.Attributes.forceFitColumns == undefined) || (object.ExtAttributes.GridOptions.Attributes.forceFitColumns == null))
                object.ExtAttributes.GridOptions.Attributes.forceFitColumns = true;
            if(!object.ExtAttributes.GridOptions.Attributes.rowHeight)
                object.ExtAttributes.GridOptions.Attributes.rowHeight = 20;
            if(!object.ExtAttributes.GridOptions.Events.onCellBlur)
                object.ExtAttributes.GridOptions.Events.onCellBlur =  object.ISGMode_CellBlur;
            if(!object.ExtAttributes.GridOptions.Events.onComplete)
                object.ExtAttributes.GridOptions.Events.onComplete =  object.ISGMode_Complete;
            if(!object.ExtAttributes.GridOptions.Title)
                object.ExtAttributes.GridOptions.Title = "";
            else
                object.ExtAttributes.GridOptions.Title = Trim(object.ExtAttributes.GridOptions.Title);
            if ((object.ExtAttributes.Editable == undefined) || (object.ExtAttributes.Editable == null))
                object.ExtAttributes.Editable = true;
            if ((object.ExtAttributes.Focused == undefined) || (object.ExtAttributes.Focused == null))
                object.ExtAttributes.Focused = false;
            if ((object.ExtAttributes.NonRefreshCount == undefined) || (object.ExtAttributes.NonRefreshCount == null))
                object.ExtAttributes.NonRefreshCount = 0;
            if ((object.ExtAttributes.NonRefreshCountMax == undefined) || (object.ExtAttributes.NonRefreshCountMax == null))
                object.ExtAttributes.NonRefreshCountMax = 5;

            return object;
        }
        catch(Error) { ShowError(Error); }
        return null;
    }
    _Grid.GridISGMode = function(options, object) {
        try {
            object = _Grid.GridISGBase(options, object);

            if (!options)
                options = {};

            object.ExtAttributes.ModeButton = null;

            object.Initialize = function (gridContainer, modeButton) {
                try {
                    object.ExtAttributes.ModeButton = modeButton;
                    object.ExtAttributes.ModeButton.className = window.FormGroup.MODEIMAGE_CLASSES.MODEIMAGE_AUTO;

                    addEventHandler(object.ExtAttributes.ModeButton, "onclick", object.ModeButton_Click);

                    object.Grid = new IndustrialSlickGrid(gridContainer, object.ExtAttributes.GridOptions);

                    object.Grid.ExtAttributes = object.ExtAttributes;

                    addEventHandler(gridContainer, "onclick", object.ISGContainers_Click);
                }
                catch(Error){ ShowError(Error); }
            }
            object.SwitchMode = function(mode, callService) {
                try {
                    if (!callService) {
                        object.ExtAttributes.ModeAuto = mode;

                        object.ExtAttributes.ModeButton.className = (object.ExtAttributes.ModeAuto)
                                                                        ? window.FormGroup.MODEIMAGE_CLASSES.MODEIMAGE_AUTO
                                                                        : window.FormGroup.MODEIMAGE_CLASSES.MODEIMAGE_MANUAL;
                        return;
                    }
                    else {
                        var errorMSG = "Could not change mode";

                        if (object.ExtAttributes.ModeAuto == mode) {
                            return;
                        }
                        else {
                            var privateParameters = new PrivateParameters(
                            {
                                URL: Global.DALServiceURL
                                , ConnectionParameters: { Async: false }
                                , DatabaseParameters: { ConnectionStringName: Global.ConnectionStringNames.SDIMes, Procedure: "dbo.SetVariableMode" }
                            });
                            privateParameters.Version.Class = "ResponseSimple";

                            var qp = new QueryParameters();
                            qp.Add("HeatNumber", "VARCHAR", object.ExtAttributes.HeatNumber);
                            qp.Add("LAV", "VARCHAR", null);
                            qp.Add("Name", "VARCHAR", object.ExtAttributes.Variable);
                            qp.Add("Mode", "BIT", mode);
                            qp.Add("ScriptName", "VARCHAR", null);
                            qp.Add("Treatment", "INT", 0);

                            ExecuteProcedure(
                                privateParameters
                                , qp
                                , function (requestData) {
                                    ValidateDALServiceResponse(
                                    {
                                        ErrorMSG: errorMSG
                                        , RequestData: requestData
                                        , Validated: function (requestData) {
                                            object.ExtAttributes.ModeAuto = mode;

                                            object.ExtAttributes.ModeButton.className = (object.ExtAttributes.ModeAuto)
                                                                                            ? window.FormGroup.MODEIMAGE_CLASSES.MODEIMAGE_AUTO
                                                                                            : window.FormGroup.MODEIMAGE_CLASSES.MODEIMAGE_MANUAL;
                                            return;
                                        }
                                        , Invalidated: function (requestData) {
                                            object.ExtAttributes.ModeButton.className = window.FormGroup.MODEIMAGE_CLASSES.MODEIMAGE_BADCOMMIT;
                                            return;
                                        }
                                    });
                                }
                                , function (requestData) {
                                    ShowError(errorMSG + ": " + requestData.text);
                                });
                        }
                    }
                }
                catch (Error) { ShowError(Error); }
            }

            object.ISGMode_RowChanged = function (row, cell, dataContext) {
                try
                {
                    object.SwitchMode(false, false);
                }
                catch(Error){ ShowError(Error); }
            };
            object.ModeButton_Click = function (e) { 
                try
                {
                    object.SwitchMode(!object.ExtAttributes.ModeAuto, true);
                }
                catch(Error){ ShowError(Error); }
            };

            if((object.ExtAttributes.GridOptions.Attributes.autoHeight == undefined) || (object.ExtAttributes.GridOptions.Attributes.autoHeight == null))
                object.ExtAttributes.GridOptions.Attributes.autoHeight = true;
            if(!object.ExtAttributes.GridOptions.Events.onRowAdded)
                object.ExtAttributes.GridOptions.Events.onRowAdded =  object.ISGMode_RowChanged;
            if(!object.ExtAttributes.GridOptions.Events.onRowDeleted)
                object.ExtAttributes.GridOptions.Events.onRowDeleted =  object.ISGMode_RowChanged;
            if(!object.ExtAttributes.GridOptions.Events.onRowEdited)
                object.ExtAttributes.GridOptions.Events.onRowEdited =  object.ISGMode_RowChanged;
            if(!object.ExtAttributes.HeatNumber)
                object.ExtAttributes.HeatNumber = "";
            else
                object.ExtAttributes.HeatNumber = Trim(object.ExtAttributes.HeatNumber);
            if ((object.ExtAttributes.ModeAuto == undefined) || (object.ExtAttributes.ModeAuto == null))
                object.ExtAttributes.ModeAuto = false;
            if(!object.ExtAttributes.Variable)
                object.ExtAttributes.Variable = "";
            else
                object.ExtAttributes.Variable = Trim(object.ExtAttributes.Variable);

            return object;
        }
        catch(Error) { ShowError(Error); }
        return null;
    }

    //#endregion

    //#endregion

    //#endregion

    return new _Grid();
})();

//#endregion

//#endregion

/*----- Global object end ----*/
/*----------------------------*/